package svc

import (
	"fmt"
	"go-zero-all-demos/apps/order/models"
	"go-zero-all-demos/apps/order/rpc/internal/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type ServiceContext struct {
	Config     config.Config
	DB         *gorm.DB
	OrderModel models.OrderModel
}

func NewServiceContext(c config.Config) *ServiceContext {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.MySQL.Username, c.MySQL.Password, c.MySQL.Path, c.MySQL.Port, c.MySQL.Dbname,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("connect mysql err:" + err.Error())
	}

	_ = db.AutoMigrate(&models.Order{})
	return &ServiceContext{
		Config:     c,
		DB:         db,
		OrderModel: models.NewOrderModel(db, c.Cache),
	}
}
